/**
 * 
 */
package com.teach.servlet.admin;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Liulianqiu
 *2020年8月4日
 */
@WebServlet("/code.let")
public class CodeServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Random r = new Random();
		String code = ""+r.nextInt(10)+r.nextInt(10)+r.nextInt(10)+r.nextInt(10);
//		request.getSession().setAttribute(Const.CODE_NAME, code);
		int width = 139;
		int height = 48;
		BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		Graphics g = img.getGraphics();//得到一个画笔对象
		//填充白色背景
		g.setColor(new Color(255,255,255));
		g.fillRect(0, 0, width, height);
		//画干扰线
		for(int i = 0; i < height/2; i++) {
			g.setColor(new Color(100+r.nextInt(150),100+r.nextInt(150),100+r.nextInt(150)));
			g.drawLine(0, r.nextInt(height), width, r.nextInt(height));
		}
		int fontSize = 36;
		g.setFont(new Font("微软雅黑", Font.BOLD, fontSize));
		int w = width/code.length();
		for(int j = 0; j < code.length(); j++) {
			g.setColor(new Color(50+r.nextInt(100), 50+r.nextInt(100), 50+r.nextInt(100)));
			g.drawString(code.substring(j,j+1), j*w, height-r.nextInt(height-fontSize));
		}
		response.reset();
		response.setContentType("image/jpeg");
		ImageIO.write(img,"jpg", response.getOutputStream());
		response.flushBuffer();
	}
}
